<template>
  <div class="role-manage">
    <div class="page-header">
      <h2>权限管理</h2>
      <div>
        <el-button type="primary" @click="handleCreateRole">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
        <el-button @click="handleViewLogs">
          <el-icon><Document /></el-icon>
          操作日志
        </el-button>
      </div>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="18">
        <el-card>
          <template #header>
            <span>角色列表</span>
          </template>
          
          <el-table :data="roleList" v-loading="loading">
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="userCount" label="用户数" width="100" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleEditRole(scope.row)">编辑</el-button>
                <el-button size="small" type="primary" @click="handleSetPermissions(scope.row)">权限</el-button>
                <el-button size="small" type="danger" @click="handleDeleteRole(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>权限模块</span>
          </template>
          
          <div class="permission-modules">
            <div class="module-item" v-for="module in permissionModules" :key="module.id">
              <div class="module-header">
                <span class="module-name">{{ module.name }}</span>
                <el-checkbox
                  :indeterminate="module.isIndeterminate"
                  v-model="module.checkAll"
                  @change="handleCheckAllChange(module)"
                >
                  全选
                </el-checkbox>
              </div>
              <div class="module-permissions">
                <el-checkbox-group v-model="selectedPermissions">
                  <el-checkbox
                    v-for="permission in module.permissions"
                    :key="permission.id"
                    :label="permission.id"
                    @change="handlePermissionChange(module)"
                  >
                    {{ permission.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogTitle"
      width="500px"
    >
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 操作日志对话框 -->
    <el-dialog
      v-model="logDialogVisible"
      title="操作日志"
      width="800px"
    >
      <el-table :data="operationLogs" v-loading="logLoading">
        <el-table-column prop="username" label="操作人" width="120" />
        <el-table-column prop="action" label="操作类型" width="120" />
        <el-table-column prop="target" label="操作对象" width="150" />
        <el-table-column prop="description" label="操作描述" />
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column prop="createTime" label="操作时间" width="180" />
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="logPagination.current"
          v-model:page-size="logPagination.size"
          :total="logPagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleLogSizeChange"
          @current-change="handleLogCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document } from '@element-plus/icons-vue'
import { permissionService } from '../../services/permissionService'

const loading = ref(false)
const logLoading = ref(false)
const roleDialogVisible = ref(false)
const logDialogVisible = ref(false)
const roleDialogTitle = ref('新增角色')
const selectedPermissions = ref([])
const roleList = ref([])
const permissionModules = ref([])
const operationLogs = ref([])

// 加载角色列表
const loadRoleList = async () => {
  try {
    loading.value = true
    const response = await permissionService.getRoleList({
      page: 0,  // 后端页码从0开始
      size: 100
    })
    roleList.value = response.data?.content || []
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 加载权限列表
const loadPermissionList = async () => {
  try {
    const response = await permissionService.getPermissionList()
    const permissions = response.data || []
    
    // 按模块分组权限
    const modules = {}
    permissions.forEach(permission => {
      const moduleName = permission.module || '其他'
      if (!modules[moduleName]) {
        modules[moduleName] = {
          id: permission.moduleId || Date.now(),
          name: moduleName,
          checkAll: false,
          isIndeterminate: false,
          permissions: []
        }
      }
      modules[moduleName].permissions.push({
        id: permission.id,
        name: permission.name
      })
    })
    
    permissionModules.value = Object.values(modules)
  } catch (error) {
    console.error('加载权限列表失败:', error)
    ElMessage.error('加载权限列表失败')
  }
}

// 加载操作日志
const loadOperationLogs = async () => {
  try {
    logLoading.value = true
    // 这里需要调用日志相关的API
    // const response = await logService.getOperationLogs({
    //   page: logPagination.current,
    //   size: logPagination.size
    // })
    // operationLogs.value = response.data?.records || []
    // logPagination.total = response.data?.total || 0
    
    // 暂时使用模拟数据
    operationLogs.value = [
      { username: 'admin', action: '新增', target: '影片', description: '新增影片《阿凡达：水之道》', ip: '192.168.1.1', createTime: '2024-01-01 10:30:00' },
      { username: 'editor1', action: '编辑', target: '分类', description: '编辑动作片分类', ip: '192.168.1.2', createTime: '2024-01-01 10:15:00' },
      { username: 'reviewer1', action: '审核', target: '评论', description: '审核通过用户评论', ip: '192.168.1.3', createTime: '2024-01-01 09:45:00' }
    ]
    logPagination.total = operationLogs.value.length
  } catch (error) {
    console.error('加载操作日志失败:', error)
    ElMessage.error('加载操作日志失败')
  } finally {
    logLoading.value = false
  }
}

const roleForm = reactive({
  id: null,
  name: '',
  description: ''
})

const handleCreateRole = () => {
  roleDialogTitle.value = '新增角色'
  Object.assign(roleForm, {
    id: null,
    name: '',
    description: ''
  })
  roleDialogVisible.value = true
}

const handleEditRole = (row) => {
  roleDialogTitle.value = '编辑角色'
  Object.assign(roleForm, { ...row })
  roleDialogVisible.value = true
}

const handleDeleteRole = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await permissionService.deleteRole(row.id)
    ElMessage.success('删除成功')
    loadRoleList() // 重新加载角色列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSetPermissions = async (row) => {
  try {
    // 获取角色当前的权限
    const response = await permissionService.getRoleDetail(row.id)
    const rolePermissions = response.data?.permissions || []
    selectedPermissions.value = rolePermissions.map(p => p.id)
    
    // 更新权限模块的选中状态
    permissionModules.value.forEach(module => {
      updateCheckAllState(module)
    })
    
    ElMessage.info(`设置角色权限: ${row.name}`)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

const handleViewLogs = () => {
  logDialogVisible.value = true
  loadOperationLogs()
}

const handleCheckAllChange = (module) => {
  const permissionIds = module.permissions.map(p => p.id)
  if (module.checkAll) {
    // 添加当前模块的所有权限
    selectedPermissions.value = [...new Set([...selectedPermissions.value, ...permissionIds])]
  } else {
    // 移除当前模块的所有权限
    selectedPermissions.value = selectedPermissions.value.filter(id => !permissionIds.includes(id))
  }
  updateCheckAllState(module)
}

const handlePermissionChange = (module) => {
  const permissionIds = module.permissions.map(p => p.id)
  const checkedCount = selectedPermissions.value.filter(id => permissionIds.includes(id)).length
  module.checkAll = checkedCount === permissionIds.length
  module.isIndeterminate = checkedCount > 0 && checkedCount < permissionIds.length
}

const updateCheckAllState = (module) => {
  const permissionIds = module.permissions.map(p => p.id)
  const checkedCount = selectedPermissions.value.filter(id => permissionIds.includes(id)).length
  module.isIndeterminate = checkedCount > 0 && checkedCount < permissionIds.length
}

const handleRoleSubmit = async () => {
  try {
    if (roleForm.id) {
      // 编辑角色
      await permissionService.updateRole(roleForm.id, {
        name: roleForm.name,
        description: roleForm.description
      })
    } else {
      // 新增角色
      await permissionService.createRole({
        name: roleForm.name,
        description: roleForm.description
      })
    }
    
    ElMessage.success(roleDialogTitle.value + '成功')
    roleDialogVisible.value = false
    loadRoleList() // 重新加载角色列表
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error(roleDialogTitle.value + '失败')
  }
}

const handleLogSizeChange = (size) => {
  logPagination.size = size
  logPagination.current = 1
  loadOperationLogs()
}

const handleLogCurrentChange = (current) => {
  logPagination.current = current
  loadOperationLogs()
}

onMounted(() => {
  loadRoleList()
  loadPermissionList()
})
</script>

<style scoped>
.role-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.permission-modules {
  max-height: 500px;
  overflow-y: auto;
}

.module-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.module-name {
  font-weight: bold;
  color: #333;
}

.module-permissions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>